from django.utils.deprecation import MiddlewareMixin
from django.conf import settings


class User(object):
    def __init__(self, id, name, avatar, user_type):
        self.id = id
        self.name = name
        self.avatar = avatar
        self.user_type = user_type


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.path_info.startswith("/admin/"):
            return

        if settings.WX_EXEMPT_AUTH:
            from www import models
            instance = models.User.objects.all().first()
            user_dict = {
                "id": instance.id, 'name': instance.name,
                'avatar': instance.avatar, 'user_type': instance.user_type
            }
            request.session['user'] = user_dict
            request.user = User(**user_dict)
            return

        request.user = None
        user_dict = request.session.get("user")  # 当登录成功  request.session['user'] = {"id":...,"name":...,"avatar":...}
        if user_dict:
            request.user = User(**user_dict)
